package com.corecloud.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.entity.*;
import com.corecloud.mapper.mysql.SysLogMapper;
import com.corecloud.mapper.mysql.SysUserMapper;
import com.corecloud.mapper.mysql.SysUserRoleMapper;
import com.corecloud.service.AafUserService;
import com.corecloud.service.SysDeptService;
import com.corecloud.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;


/**
 * 实现security用户相关
 */
@Service
@Primary
public class CustomUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private AafUserService aafUserService;
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysUserRoleMapper userRoleMapper;
	@Autowired
	private SysLogMapper sysLogMapper;



	/**
	 * Locates the user based on the username. In the actual implementation, the search
	 * may possibly be case sensitive, or case insensitive depending on how the
	 * implementation instance is configured. In this case, the <code>UserDetails</code>
	 * object that comes back may have a username that is of a different case than what
	 * was actually requested..
	 *
	 * @param username the username identifying the user whose data is required.
	 * @return a fully populated user record (never <code>null</code>)
	 * @throws UsernameNotFoundException if the user could not be found or the user has no
	 *                                   GrantedAuthority
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		if(StringUtils.isEmpty(username)){ throw new UsernameNotFoundException("参数异常,请确认后登录"); }

		/**
		 * 用户信息验证流程
		 * 1：大唐数据库验证对应数据查询是否存在对应用户
		 * 2：如果存在则直接使用大唐方面用户数据进行登录
		 * 3：如不存在则查询本平台用户数据进行匹配
		 */
		String pwd = "";
		//大唐用户数据验证获取
//		Map<String,Object> au = aafUserService.getInfoByUserName(username);
		Map<String,Object> au = new HashMap<>();
		SysUserEntity user = userMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",username));

		if((au == null || au.size() ==0) && user == null){
			//插入登录日志
			SysLogEntity sysLog = new SysLogEntity();
			sysLog.setUrl("/login");
			sysLog.setUserName(username);
			sysLog.setCreateTime(new Date());
			sysLog.setMsg("用户不存在,请确认后登录");
			sysLogMapper.insert(sysLog);
			throw new UsernameNotFoundException("用户不存在,请确认后登录");
		}

		//大唐用户主体数据存在此用户，mysql库没有这个用户，需要添加此用户
		if(au != null && user == null){
			SysUserEntity newUser = new SysUserEntity();
			newUser.setUserName(username);
			newUser.setPassword(au.get("PASSWORD").toString());
			newUser.setIsValid(1);
			newUser.setCreateTime(new Date());
			newUser.setSource(3);
			if(!StringUtils.isEmpty(au.get("USER_NAME"))){
				newUser.setNickName(au.get("USER_NAME").toString().trim());
				newUser.setName(au.get("USER_NAME").toString().trim());
			}

			//回填用户机构与地区相关信息,如果查询不到机构则默认设置该用户为河南省用户
			if(!StringUtils.isEmpty(au.get("school"))){
				SysDeptEntity dept = sysDeptService.selectOne(new QueryWrapper<SysDeptEntity>().eq("dept_name",au.get("SCHOOL").toString().trim()));
				if(dept!=null && !StringUtils.isEmpty(dept.getDeptCode())){ newUser.setDeptId(dept.getId()); }

				if(dept!=null && !StringUtils.isEmpty(dept.getAreaId())){
					newUser.setAreaId(dept.getAreaId());

				}else{ newUser.setAreaId("410000"); }

			}else{ newUser.setAreaId("410000"); }


			//插入数据，新用户统一默认为教师角色
			try{
				userMapper.insert(newUser);
				user = userMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",username));
				SysUserRoleEntity sur = new SysUserRoleEntity();
				sur.setRoleId(25);
				sur.setRoleState(1);
				sur.setRoleName("老师");
				sur.setRoleCode("TEACHER");
				sur.setUserId(newUser.getId());
				sysUserRoleService.insertInfo(sur);
			}catch (Exception e){ throw new UsernameNotFoundException("登录失败，请联系管理员"); }
		}

		//设置用户需要比对的密码
		if(au != null && !StringUtils.isEmpty(au.get("PASSWORD"))){
			pwd = au.get("PASSWORD").toString();
		}else{
			pwd = user.getPassword();
		}

		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		List<SysUserRoleEntity> userRoleList =  userRoleMapper.selectList(new QueryWrapper<SysUserRoleEntity>().eq("user_id",user.getId()));
		List<String> authorityName = new ArrayList<>();
		for(int i = 0;i<userRoleList.size();i++){
			SysUserRoleEntity sr = userRoleList.get(i);
			if(sr.getRoleState() == 1){
				authorityName.add("ROLE_"+userRoleList.get(i).getRoleCode());
			}
		}
		for(String roleName : authorityName) {
			SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
			auths.add(authority);
		}
		return new org.springframework.security.core.userdetails.User(username,pwd,true,true,true,true,auths);
	}

}
